package tree.simple;

import tree.TreeNode;

/**
 * 平衡二叉树
 * 输入：root = [3,9,20,null,null,15,7]
 * 输出：true
 * 示例 2：
 *
 *
 * 输入：root = [1,2,2,3,3,null,null,4,4]
 * 输出：false
 * 示例 3：
 *
 * 输入：root = []
 * 输出：true
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/balanced-binary-tree
 */
public class BalancedBinaryTree_110 {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }else{
            return dfs(root) >= 1;
        }

    }

    public int dfs(TreeNode node) {
        if (node == null){
            return 0;
        }
        int leftDfs = dfs(node.left);
        int rightDfs = dfs(node.right);
        if (leftDfs == -1 || rightDfs == -1 || Math.abs(leftDfs - rightDfs) > 1) {
            return -1;
        } else {
            return Math.max(leftDfs, rightDfs) + 1;
        }
    }

}
